<template>
  <van-loading v-if="loading" class="loading" />
  <van-nav-bar left-arrow v-if="commentsNumber" @click-left="onClickLeft">
    <template #title>{{ commentsNumber }}条评论</template>
  </van-nav-bar>
  <!-- 长评 -->
  <div class="comments" v-if="longCommentsNumber > 0">
    <div class="title">{{ longCommentsNumber }}条长评</div>
    <div class="long" v-for="comment in longComments" :key="comment.id">
      <img class="avatar" :src="comment.avatar" :alt="comment.author">
      <div class="author-content">
        <span class="author">{{ comment.author }}</span>
        <van-icon name="ellipsis" @click="toggleAction(comment.id)" class="ellipsis" />
        <ul v-show="showAction[comment.id]" class="action">
          <li>
            <div class="copy" :data-clipboard-target="`#content-${comment.id}`" @click.stop="copyContent(comment.id)">复制
            </div>
          </li>
          <li>
            <div class="report">举报</div>
          </li>
        </ul>
        <div class="content" :id="`content-${comment.id}`">{{ comment.content }}</div>
        <div class="pubDate-social">
          <div class="pubDate">{{ formatTimestamp(comment.time) }}</div>
          <div class="social">
            <span v-if="comment.likes > 0">{{ comment.likes }} </span> <van-icon name="good-job-o" size="20" />
            <van-icon name="chat-o" size="20" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 短评 -->
  <div class="comments" v-if="shortCommentsNumber > 0">
    <div class="title">{{ shortCommentsNumber }}条短评</div>
    <div class="short" v-for="comment in shortComments" :key="comment.id">
      <img class="avatar" :src="comment.avatar" :alt="comment.author">
      <div class="author-content">
        <span class="author">{{ comment.author }}</span>
        <van-icon name="ellipsis" @click="toggleAction(comment.id)" class="ellipsis" />
        <ul v-show="showAction[comment.id]" class="action">
          <li>
            <div class="copy" :data-clipboard-target="`#content-${comment.id}`" @click.stop="copyContent(comment.id)">复制
            </div>
          </li>
          <li>
            <div class="report">举报</div>
          </li>
        </ul>
        <div class="content" :id="`content-${comment.id}`">
          <div class="currentComment"> {{ comment.content }}</div>
          <div class="reply-to" v-if="comment.reply_to">
            // {{ comment.reply_to.author }}:{{ comment.reply_to.content }}
          </div>
        </div>
        <div class="pubDate-social">
          <div class="pubDate">{{ formatTimestamp(comment.time) }}</div>
          <div class="social">
            <span v-if="comment.likes > 0">{{ comment.likes }} </span> <van-icon name="good-job-o" size="20" />
            <van-icon name="chat-o" size="20" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { formatTimestamp } from "@/tools/index.js"
import { ref, onMounted, computed } from 'vue'
import { getShortComments, getMoreShortComments, getLongComments, getMoreLongComments } from "@/api/index.js"
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const showAction = ref({})  // { commentId: boolean }
const articleId = ref(route.params.articleId)
const longComments = ref([])
const shortComments = ref([])

const shortCommentsNumber = computed(() => shortComments.value.length)
const longCommentsNumber = computed(() => longComments.value.length)
const commentsNumber = computed(() => longComments.value.length + shortComments.value.length)

onMounted(async () => {
  const short = await getShortComments(articleId.value)
  shortComments.value = short.comments
  const long = await getLongComments(articleId.value)
  longComments.value = long.comments
  loading.value = false


  // 初始化 showAction 状态
  longComments.value.forEach(comment => {
    showAction.value[comment.id] = false;
  });
  shortComments.value.forEach(comment => {
    showAction.value[comment.id] = false;
  });
  console.log("showAction", showAction.value);
});


function onClickLeft () {
  router.push({ path: `/article/${articleId.value}` })
}



function toggleAction (commentId) {
  // 如果当前评论项的 action 已经显示，则隐藏它
  if (showAction.value[commentId]) {
    showAction.value[commentId] = false;
  } else {
    // 否则，关闭所有其他评论项的 action 并显示当前评论项的 action
    Object.keys(showAction.value).forEach(id => {
      if (id !== commentId) {
        showAction.value[id] = false;
      }
    })
    showAction.value[commentId] = true;
  }
}

async function copyContent (commentId) {
  try {
    // 确保选择器能正确找到元素
    const contentElement = document.querySelector(`#content-${commentId}`)
    if (!contentElement) throw new Error('找不到评论内容元素')

    // 明确获取文本内容
    const content = contentElement.innerText
    if (!content.trim()) throw new Error('评论内容为空')

    // 现代浏览器复制方案
    await navigator.clipboard.writeText(content)
    console.log('复制成功:', content)
    showAction.value[commentId] = false
  } catch (err) {
    console.error('复制失败:', err)

    // 兼容方案需要重新获取内容
    const contentElement = document.querySelector(`#content-${commentId}`)
    if (!contentElement) {
      alert('无法定位到要复制的内容')
      return
    }

    const content = contentElement.innerText
    const textArea = document.createElement('textarea')
    textArea.value = content
    textArea.style.position = 'fixed'  // 避免页面滚动
    document.body.appendChild(textArea)
    textArea.select()

    try {
      const success = document.execCommand('copy')
      if (!success) throw new Error('execCommand 执行失败')
      console.log('传统方式复制成功')
    } catch (error) {
      alert(`复制失败，请手动选择内容复制。错误信息：${error.message}`)
    } finally {
      document.body.removeChild(textArea)
    }
  }
}
</script>

<style scoped>
.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.comments {
  padding: 5px 0;
}

.comments .title {
  margin-bottom: 20px;
  padding-left: 15px;
}

.long,
.short {
  display: grid;
  grid-template-columns: 1fr 10fr;
  grid-gap: 10px;
  border-bottom: 1px solid #eee;
  padding: 0 15px 15px 15px;
  margin-top: 15px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.author-content {
  position: relative;
  font-size: 18px;
}

.ellipsis {
  float: right;
}

.content {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 20px;
  margin-top: 10px;
}

.reply-to {
  font-size: 14px;
  color: #666;
}

.action {
  width: calc(100vw - 70%);
  position: absolute;
  top: 25px;
  right: -15px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  font-size: 16px;
  height: 60px;
  z-index: 10;
  box-shadow: 2px 5px 10px rgb(197 194 193);
  padding: 10px;
}

.action li {
  padding: 5px 0;
}

.pubDate-social {
  color: #999;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center
}

:deep(i.van-badge__wrapper.van-icon.van-icon-good-job-o) {
  margin-right: 30px;
}
</style>
